<template>
  <div class="contentBox">
    <div class="btnBox">
      <el-button
        type="primary"
        @click="addRole"
      >
        新建岗位
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column
        prop="code"
        label="岗位编码"
        width="280"
      />
      <el-table-column
        prop="name"
        label="岗位名称"
        width="280"
      />
      <el-table-column
        prop="remark"
        label="岗位描述"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        prop="status"
        label="状态"
        width="180"
      >
        <template slot-scope="scope">
          {{ scope.row.status==1?'启用':'禁用' }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="400"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            @click="selectUser(scope.row)"
          >
            人员管理
          </el-button>
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            @click="editRole(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            class="MR18 bg5584FF"
            type="primary"
            @click="deleteRole(scope.row.position_id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageBox">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-size="10"
        layout="prev, pager, next, jumper"
        :total="total"
        @current-change="geTabdata"
      />
    </div>
    <!-- 新增角色 -->
    <el-dialog
      title="新增岗位"
      :visible.sync="addDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        v-loading="addLoading"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 input40"
      >
        <el-form-item
          label="岗位编码"
          :rules="[
                {
                  required: true,
                  validator: codeRules,
                  trigger: ['blur']
                }
              ]"
          prop="code"
        >
          <el-input
            v-model="ruleForm.code"
            maxlength="20"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item
          label="岗位名称"
          prop="name"
        >
          <el-input
            v-model="ruleForm.name"
            maxlength="20"
            placeholder="请输入"
          />
        </el-form-item>

        <el-form-item label="岗位状态：">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="1">
              启用
            </el-radio>
            <el-radio label="0">
              禁用
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="岗位描述">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
          />
        </el-form-item>
        <div class="formBtnBox">
          <el-button
            type="primary"
            @click="submitForm('ruleForm')"
          >
            提交
          </el-button>
          <el-button @click="addDialogVisible = false">
            取消
          </el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 编辑角色 -->
    <el-dialog
      title="编辑岗位"
      :visible.sync="editDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="editHandleClose"
    >
      <el-form
        ref="editRuleForm"
        :model="editRuleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 input40"
      >
        <el-form-item
          label="岗位编码"
          prop="code"
        >
          <el-input
            v-model="editRuleForm.code"
            disabled
            maxlength="20"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item
          label="岗位名称"
          maxlength="20"
          prop="name"
        >
          <el-input v-model="editRuleForm.name" />
        </el-form-item>

        <el-form-item
          label="岗位状态："
          prop="state"
        >
          <el-radio-group v-model="editRuleForm.status">
            <el-radio label="1">
              启用
            </el-radio>
            <el-radio label="0">
              禁用
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="岗位描述"
          prop="remark"
        >
          <el-input
            maxlength="200"
            v-model="editRuleForm.remark"
            type="textarea"
          />
        </el-form-item>
        <div class="formBtnBox">
          <el-button
            type="primary"
            @click="editSubmitForm('editRuleForm')"
          >
            提交
          </el-button>
          <el-button @click="editDialogVisible = false">
            取消
          </el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="删除岗位"
      :visible.sync="delDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>确认要删除该岗位？此操作不可逆</p>
      <div class="formBtnBox">
        <el-button
          type="primary"
          @click="sureDelete"
        >
          确定
        </el-button>
        <el-button @click="delDialogVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <!-- 人员管理 -->
    <el-dialog
      v-if="userDialogVisible"
      title="人员选择"
      :visible.sync="userDialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <base-table
        :row-header="headerConfig"
        :table-data="userTableData"
        :table-config="tableConfig"
        :is-selection="isSelection"
        :selected-rows="selectedRows"
        @getSelectData="getSelectData"
        @changePage="changePage"
        @confirmData="confirmData"
      />
    </el-dialog>
  </div>
</template>
<script>
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'
import { getRandomId } from '@/utils';
import baseTable from '@/components/baseTable'
import { v4 as uuidv4 } from "uuid";
export default {
  components: {
    baseTable
  },
  data() {
    return {
      tableConfig:{
        list: [],
        pageNum: 1,
        pageSize: 10,
        total: null
      },
      isSelection:true,
      headerConfig:[
        {
          'prop':'account',
          'label':'登录名'
        },
        {
          'prop':'name',
          'label':'姓名'
        },
        {
          'prop':'email',
          'label':'邮箱'
        },
        {
          'prop':'dept_name',
          'label':'部门'
        }
      ],
      innerPage:1,
      selectPosition:null,
      userTableData: {},
      selectUsers:[],
      addDialogVisible: false,
      editDialogVisible: false,
      delDialogVisible: false,
      userDialogVisible: false,
      allotRoleDialogVisible: false,
      selectedRows:[],
      loading: false,
      addLoading: false,
      editLoading: false,
      currentPage: 1,
      current: 1,
      total: 0,
      roleId: undefined,
      defaultChecked: [],
      ruleForm: {
        status: '1'
      },
      editRuleForm: {},
      rules: {
        code: [{ required: true, message: '请输入岗位编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }]
      },

      tableData: [],
      treeData: [],
      defaultProps: {
        children: 'childs',
        label: 'name'
      }
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    this.geTabdata()
  },
  methods: {
    codeRules(rule, value, callback) {
      if (value) {
        this.COM.jsonsqlForSelect({
          "sys_position:data[]": {
            "@column": "code", //定义返回列
            "@where": {
              // 查询条件
              "code@eq": value.trim()
            }
          }
        }).then(res => {
          if (res.data && res.data.length == 0) {
            callback();
          } else {
            callback(new Error("编码重复"));
          }
        })
      } else {
        callback("请输入");
      }
    },
    geTabdata() {
      this.loading = true
      const params = {
        'sys_position:data[]':{
          '@column':'*',
          '@page':{
            '@pageNo':this.currentPage,
            '@pageSize':10,
          },
          '@order':'create_time-'
        }
      }
      this.COM.jsonsqlForSelect(params).then(res =>{
        this.tableData = res.data
        this.total = parseInt(res.total)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    selectUser(row){
      this.selectPosition = row
      this.innerPage = 1
      this.getUserData()
    },
    addRole() {
      this.addDialogVisible = true
    },
    submitForm(formName) {
      // 表单提交
      this.addLoading = true
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.ruleForm.position_id = getRandomId(false,10)
          this.ruleForm.create_time = new Date()
          this.COM.jsonsqlForInsert({
            'sys_position':[
              this.ruleForm
            ]
          }).then(() =>{
            Message.success('创建成功')
            this.$set(this.ruleForm, 'remark', '')
            this.addDialogVisible = false
            this.addLoading = false
            this.geTabdata()
          }).catch(() =>{
            this.addLoading = false
          })
        } else {
          console.log('error submit!!')
          this.addLoading = false
          return false
        }
      })
    },
    editRole(row) {
      this.editDialogVisible = true
      this.editRuleForm = JSON.parse(JSON.stringify(row))
      console.log('editRuleForm:', this.editRuleForm)
    },
    editSubmitForm(formName) {
      // 编辑表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          const updateParams = {
            'sys_position':{
              'name': this.editRuleForm.name,
              'remark': this.editRuleForm.remark,
              'status': this.editRuleForm.status,
              '@where':{
                'position_id@eq':this.editRuleForm.position_id
              }
            }
          }
          this.COM.jsonsqlForUpdate(updateParams).then(() =>{
            Message.success('修改成功')
            this.editDialogVisible = false
            this.geTabdata()
          }).catch(() =>{
            this.addLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    deleteRole(roleId) {
      this.roleId = roleId
      this.delDialogVisible = true
    },
    sureDelete() {
      this.COM.jsonsqlForDelete({
        'sys_position':{
          '@where':{
            'position_id@eq':this.roleId
          }
        }
      }).then(() =>{
        Message.success('删除岗位成功')
        this.geTabdata()
        this.delDialogVisible = false
      })
    },
    addHandleClose() {
      this.$refs.ruleForm.resetFields()
      if (this.ruleForm.remark) {
        this.$set(this.ruleForm, 'remark', '')
      }
    },
    editHandleClose() {
      this.$refs.editRuleForm.resetFields()
    },
    changePage(page){
      this.innerPage = page
      this.getUserData()
    },
    getUserData(){
      const params = {
        'sys_user:data[]':{
          '@column':'user_id,user_id:id,account,name,email',
          '@where':{
            'status@eq':'ENABLE'
          },
          '@page':{
            '@pageNo':this.innerPage,
            '@pageSize':10
          },
          '@join':[
            {
              'sys_dept@leftOutJoin':{
                '@column':'simple_name:dept_name',
                '@on':{
                  'dept_id':'data/dept_id'
                }
              }
            }
          ]
        }
      }
      const querySelect = {
        'sys_user:data[]':{
          '@column':'user_id:id',
          '@where':{
            'status@eq':'ENABLE'
          },
          '@join':[
            {
              'sys_user_pos@leftOutJoin':{
                '@column':'pos_id',
                '@on':{
                  'user_id':'data/user_id'
                },
                '@where':{
                  'pos_id@eq':this.selectPosition.position_id
                }
              }
            }
          ]
        }
      }

      this.COM.jsonsqlForSelect(params).then(res => {
        this.$set(this.userTableData,'list', res.data)
        this.$set(this.userTableData,'total', parseInt(res.total))
        this.COM.jsonsqlForSelect(querySelect).then(res => {
          this.selectedRows = res.data.map(item => item.id)
          this.userDialogVisible = true
        })
      })
    },
    getSelectData(data){
      this.selectUsers = data
    },
    confirmData(){
      this.userDialogVisible = false
      const arr = this.selectUsers.map(user => {
        return {
          'user_pos_id':uuidv4(),
          'user_id': '' + user.id,
          'pos_id':'' + this.selectPosition.position_id
        }
      })
      if(arr.length > 0){
        this.COM.jsonsqlForDelete({
          'sys_user_pos':{
            '@where':{
              'pos_id@eq':'' + this.selectPosition.position_id
            }
          }
        }).then(() => {
          this.COM.jsonsqlForInsert({
            'sys_user_pos':arr
          }).then(() =>{
            Message.success('人员配置成功')
          }).catch(() =>{
            Message.error('人员配置失败')
          })
        })
      }
    }
  }
}
</script>
